import 'package:get/get.dart';
import 'package:logger/logger.dart';
import 'package:tencent_cloud_chat_sdk/enum/V2TimAdvancedMsgListener.dart';
import 'package:tencent_cloud_chat_sdk/manager/v2_tim_message_manager.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_conversation.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_message.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_msg_create_info_result.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_value_callback.dart';
import 'package:tencent_cloud_chat_sdk/tencent_im_sdk_plugin.dart';
import 'package:vischat/core/typedefs/function.dart';

/// 消息处理
class MessageUtil {
  MessageUtil._();

  static final Logger _logger = Get.find<Logger>();
  static final V2TIMMessageManager v2timMessageManager =
      TencentImSDKPlugin.v2TIMManager.getMessageManager();

  static Future<List<V2TimMessage>?> getMessageList({
    required String userID,
    String? lastMsgID,
  }) async {
    try {
      final result = await v2timMessageManager.getHistoryMessageList(
        userID: userID,
        count: 20,
        lastMsgID: lastMsgID,
      );
      if (result.code == 0) {
        return result.data;
      } else {
        _logger.e("获取历史消息失败: ${result.code} - ${result.desc}");
        return null;
      }
    } catch (e) {
      _logger.e("获取历史消息异常: $e");
      return null;
    }
  }

  static Future<void> addAdvancedMsgListener(
    V2TimAdvancedMsgListener listener,
  ) async {
    await v2timMessageManager.addAdvancedMsgListener(listener: listener);
  }

  static Future<void> removeAdvancedMsgListener() async {
    await v2timMessageManager.removeAdvancedMsgListener();
  }

  /// 消息已读
  static Future<void> markMessagesRead(V2TimConversation conversation) async {
    if (conversation.groupID != null) {
      await v2timMessageManager.markGroupMessageAsRead(
        groupID: conversation.groupID!,
      );
    } else {
      await v2timMessageManager.markC2CMessageAsRead(
        userID: conversation.userID!,
      );
    }
  }

  /// 创建文字消息
  static Future<String> createTextMessage({
    required String text,
  }) async {
    V2TimValueCallback<V2TimMsgCreateInfoResult> res = await v2timMessageManager
        .createTextMessage(text: text);
    return res.data?.id??'';
  }

  static Future<String> createImageMessage({
    required String imagePath,
  }) async {
    V2TimValueCallback<V2TimMsgCreateInfoResult> res = await v2timMessageManager
        .createImageMessage(imagePath: imagePath);
    return res.data?.id??'';
  }

  static Future<void> sendMessage({
    required String id,
    required String receiver,
    required String groupID,
    SendMsgCallBack? callBack,
  }) async {
    V2TimValueCallback<V2TimMessage> sendMessageRes = await v2timMessageManager
        .sendMessage(id: id, receiver: receiver, groupID: groupID);
    callBack?.call(sendMessageRes.data);
  }
}
